"""
合同解析的api服务接口
"""
import json
from typing import Dict
from server.api_wrap import async_api_wrapper, BaseResponse
from core.milvus_vector import MilvusVector
from core.parse import ContractParser
from core.config import settings
from fastapi import Body
from loguru import logger


@async_api_wrapper
async def contract_parse_api(
        contract_data: Dict = Body(description='合同的json数据', examples=None)
):
    """
    合同数据的清洗，分块，和 Embedding入库milvus
    """
    logger.info(f'传入数据: {json.dumps(contract_data, ensure_ascii=False)}')
    info = {key: value for key, value in contract_data.items() if key in ['fileId', 'documentName']}
    logger.info(f'合同解析入库: {json.dumps(info, ensure_ascii=False)}')

    # 清洗和分割文本块
    parser = ContractParser(
        chunk_size=settings.CHUNK_SIZE,
        chunk_overlap=settings.CHUNK_OVERLAP
    )
    documents = parser.parse(contract_data)
    if settings.DEBUG:
        logger.debug('分块后的文本列表：')
        for doc in documents:
            logger.debug({'content': doc.content})

    # Embedding及入库milvus
    milvus = MilvusVector()
    milvus.create(collection_name=contract_data['fileId'], documents=documents)

    logger.info(f'合同入库完成: {json.dumps(info, ensure_ascii=False)}')
    return BaseResponse()
